package cn.example.practice.service;

import cn.example.practice.db.GoodsDao;
import cn.example.practice.model.Goods;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class GoodsService {
    private static final Logger LOGGER = Logger.getLogger(GoodsService.class.getName());
    private final GoodsDao goodsDao;

    public GoodsService() {
        this.goodsDao = new GoodsDao();
    }

    public List<Goods> calculateSelectedGoods(String[] selectedIds, Map<String, String> countMap) {
        if (selectedIds == null || selectedIds.length == 0) {
            return new ArrayList<>();
        }

        try {
            List<Integer> idList = Arrays.stream(selectedIds)
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            List<Goods> goodsList = goodsDao.getGoodsByIds(idList);

            return goodsList.stream()
                    .peek(goods -> {
                        try {
                            String countStr = countMap.get(goods.getId());
                            int count = Integer.parseInt(countStr.trim());
                            goods.setCount(count);
                        } catch (Exception e) {
                            LOGGER.log(Level.WARNING, "Error parsing count for goods ID: " + goods.getId(), e);
                            goods.setCount(0);
                        }
                    })
                    .collect(Collectors.toList());
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error retrieving goods from database", e);
            throw new RuntimeException("Failed to retrieve goods from database", e);
        }
    }

    public float calculateTotal(List<Goods> goodsList) {
        if (goodsList == null) {
            return 0.0f;
        }

        return (float) goodsList.stream()
                .mapToDouble(Goods::getTotal)
                .sum();
    }
}
